package com.ez.supervise.action.biz;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.ez.supervise.action.base.BaseJsonAction;
import com.ez.supervise.core.Page;
import com.ez.supervise.core.Result;
import com.ez.supervise.model.base.BaseEntity;
import com.ez.supervise.model.biz.File;
import com.ez.supervise.service.FileService;
import com.ez.supervise.util.ConvertUtil;
import com.ez.supervise.util.FreemarkerUtil;

public class FileAction extends BaseJsonAction {
    private static final long serialVersionUID = 8735170970520475073L;
    private Long id;
    private FileService fileService;
    private File file;

    private Page page;

    private java.io.File doc;
    private String fileName;
    private String ids;

    public String saveFile() {
	getResponse().setContentType("text/html; charset=UTF-8");
	try {
	    // save file
	    if (doc != null) {
		String folder = file.getFolder();
		String targetDirectory = targetDirectory();
		if (StringUtils.isNotBlank(folder)) {
		    targetDirectory += "/" + folder.trim();
		}
		String targetFileName = generateFileName(fileName);
		java.io.File target = new java.io.File(targetDirectory, targetFileName);
		FileUtils.copyFile(doc, target);
		file.setFilePath(targetFileName);
	    }
	    if (file.isNew()) {
		fileService.insert(file);
	    } else {
		// delete old file
		File oldFile = (File) fileService.get(file.getId());
		if (oldFile != null && StringUtils.isNotBlank(oldFile.getFilePath())) {
		    String folder = oldFile.getFolder();
		    String targetDirectory = targetDirectory();
		    if (StringUtils.isNotBlank(folder)) {
			targetDirectory += "/" + folder.trim();
		    }
		    java.io.File file = new java.io.File(targetDirectory, oldFile.getFilePath());
		    file.delete();
		}
		fileService.update(file);
	    }
	    Result result = new Result(file.getId());
	    result.setEntity(file);
	    JsonConfig config = new JsonConfig();
	    config.setExcludes(new String[] { "creator", "createTime", ",modifier", "modifyTime", "isDeleted", "new",
		"content" });
	    outString(JSONObject.fromObject(result, config).toString());
	} catch (Exception e) {
	    e.printStackTrace();
	    outString(RESULT_FAIL);
	}
	return SUCCESS;
    }

    public String findAllFile() {
	page = new Page();
	String searchField = getRequest().getParameter("searchField");
	String searchValue = getRequest().getParameter("searchValue");
	if (StringUtils.isNotBlank(searchValue)) {
	    page.putCondition(searchField, searchValue.trim());
	}
	int start = Integer.valueOf(getRequest().getParameter("start"));
	int limit = Integer.valueOf(getRequest().getParameter("limit"));
	page.setStart(++start);
	page.setLimit(limit = limit == 0 ? 20 : limit);
	page.addPageInfo();
	page = fileService.findFileByPage(page);

	JsonConfig config = new JsonConfig();
	config.setExcludes(new String[] { "creator", "createTime", ",modifier", "modifyTime", "isDeleted", "new", });

	JSONObject jsonObj = JSONObject.fromObject(page, config);
	// System.out.println(jsonObj.toString());
	outJsonString(jsonObj.toString());
	return SUCCESS;
    }

    public String findAll() {
	page = new Page();
	page.setTotalProperty(0);
	page.setRoot(fileService.findAll());

	JsonConfig config = new JsonConfig();
	config.setExcludes(new String[] { "creator", "createTime", ",modifier", "modifyTime", "isDeleted", "new", });

	JSONObject jsonObj = JSONObject.fromObject(page, config);
	// System.out.println(jsonObj.toString());
	outJsonString(jsonObj.toString());
	return SUCCESS;
    }

    /**
     * @return
     */
    public String deleteFile() {
	try {
	    if (id != null && id > 0) {
		File oldFile = (File) fileService.get(id);
		if (oldFile != null && StringUtils.isNotBlank(oldFile.getFilePath())) {
		    String folder = oldFile.getFolder();
		    String targetDirectory = targetDirectory();
		    if (StringUtils.isNotBlank(folder)) {
			targetDirectory += "/" + folder.trim();
		    }
		    java.io.File file = new java.io.File(targetDirectory, oldFile.getFilePath());
		    file.delete();
		}
		fileService.delete(id);
	    }
	    outJsonString(RESULT_SUCCESS);
	} catch (Exception e) {
	    outJsonString(RESULT_FAIL);
	}
	return SUCCESS;
    }

    /**
     * @return
     * @throws Exception
     */
    public String updateFile() throws Exception {
	String fieldName = getRequest().getParameter("fieldName");
	String fieldValue = getRequest().getParameter("fieldValue");
	String strfileId = getRequest().getParameter("id");
	try {
	    if (id != null && id > 0) {
		File savefile = new File();
		savefile.setId(id);
		BeanUtils.setProperty(savefile, fieldName, fieldValue);
		fileService.update(savefile);
	    }
	    outJsonString(RESULT_SUCCESS);
	} catch (Exception e) {
	    outJsonString(RESULT_FAIL);
	}

	return SUCCESS;
    }

    public String publish() {
	try {
	    if (StringUtils.isNotEmpty(ids)) {
		List idList = ConvertUtil.convertIdList(ids);
		fileService.publish(idList,BaseEntity.STATUS_PUBLISH_YES);
		List publishList = fileService.findFileByPublish();
		boolean flag = createHtml(publishList);
		if(!flag){
		    outJsonString(RESULT_FAIL);
		    return SUCCESS;
		}
	    }
	    outJsonString(RESULT_SUCCESS);
	} catch (Exception e) {
	    e.printStackTrace();
	    outJsonString(RESULT_FAIL);
	}
	return SUCCESS;
    }

    private boolean createHtml(List result) {
	boolean flag = true;
	boolean create = FreemarkerUtil.createHtml("index-file.ftl", new HashMap(), WEB_SITE_PATH, "index-file.htm");
	Map<String, List> resultMap = filter(result);
	for (Iterator<String> iter = File.getFolderMap().keySet().iterator(); iter.hasNext();) {
	    String key = iter.next();
	    List dataList = resultMap.get(key);
	    if (dataList == null) {
		dataList = new ArrayList();
	    }
	    Map contents = new HashMap();
	    contents.put("result", dataList);
	    create = FreemarkerUtil.createHtml("file.ftl", contents, WEB_SITE_PATH, "file-" + key + ".htm");
	    if (!create) {
		flag = false;
	    }
	}
	return flag;
    }
    
    private static Map<String, List> filter(List fileList) {
	Map resultMap = new HashMap<String, List>();
	if (fileList == null || fileList.isEmpty()) {
	    return resultMap;
	} else {
	    List srcList = new ArrayList(fileList);
	    for (Iterator<String> iter = File.getFolderMap().keySet().iterator(); iter.hasNext();) {
		List result = new ArrayList();
		String key = iter.next();
		for (Iterator<File> item = fileList.iterator(); item.hasNext();){
		    File  nf = item.next();
		    if (key.equalsIgnoreCase(nf.getFolder())) {
			result.add(nf);
			item.remove();
		    }
		}
//		if(!result.isEmpty()) {
		    resultMap.put(key, result);
//		}
	    }
	    return resultMap;
	}
    }

    public String recall() {
	try {
	    if (StringUtils.isNotEmpty(ids)) {
		List idList = ConvertUtil.convertIdList(ids);
		fileService.publish(idList,BaseEntity.STATUS_PUBLISH_NO);
		List publishList = fileService.findFileByPublish();
		boolean flag = createHtml(publishList);
		if(!flag){
		    outJsonString(RESULT_FAIL);
		    return SUCCESS;
		}
	    }
	    outJsonString(RESULT_SUCCESS);
	} catch (Exception e) {
	    e.printStackTrace();
	    outJsonString(RESULT_FAIL);
	    return SUCCESS;
	}
	return SUCCESS;
    }
    
    private String targetDirectory() {
	return ServletActionContext.getServletContext().getRealPath("/") + UPLOAD_FILE_PATH;
    }

    private String generateFileName(String fileName) {
	DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
	String formatDate = format.format(new Date());

	int random = new Random().nextInt(10000);
	if (StringUtils.isNotBlank(fileName)) {
	    int position = fileName.lastIndexOf(".");
	    String extension = fileName.substring(position);
	    return formatDate + random + extension;
	} else {
	    return formatDate + random;
	}

    }

    public Long getId() {
	return id;
    }

    public void setId(Long id) {
	this.id = id;
    }

    public File getFile() {
	return file;
    }

    public void setFile(File file) {
	this.file = file;
    }

    public String getFileName() {
	return fileName;
    }

    public void setFileName(String fileName) {
	this.fileName = fileName;
    }

    public void setDoc(java.io.File file) {
	this.doc = file;
    }

    public void setDocFileName(String fileName) {
	this.fileName = fileName;
    }

    public void setPage(Page page) {
	this.page = page;
    }

    public void setFileService(FileService fileService) {
	this.fileService = fileService;
    }

    public void setIds(String ids) {
	this.ids = ids;
    }

    public String getIds() {
	return ids;
    }

}
